package adapter;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DbAdapter {
	private static final String KEYNAME = "name";
	private static final String KEYAGE = "age";
	private static final String DB_TABLE = "mainTable";
	private DbOpenHelper dBHelper;
	private Context context;
	private SQLiteDatabase db;

	public DbAdapter(Context context) {
		this.context = context;
		this.dBHelper = new DbOpenHelper(context);
	}
	
	public DbAdapter open() throws SQLException {
		try {
			db = dBHelper.getWritableDatabase();
		} catch (Exception e) {
			// TODO: handle exception
			db = dBHelper.getReadableDatabase();
		}
		return this;
	}
	public void close(){
		db.close();
	}
	
	public Boolean isOpen()
	{
		return db.isOpen();
	}

	public long insert(DBObject dbObject) {
		try {
			ContentValues cv = new ContentValues();
			cv.put(KEYNAME, dbObject.getName());
			cv.put(KEYAGE, dbObject.getAge());
			return db.insert(DB_TABLE, null, cv);
		} catch (Exception e) {
			// TODO: handle exception
			Log.v("tag", "err insert" + e.toString());
			return -1;
		}
	}
	
	public int removeAt(String name){
		String whereClause = "name = '" + name + "'";
		return db.delete(DB_TABLE, whereClause , null);
	}
	public int removeAll()
	{
		return db.delete(DB_TABLE, null, null);
	}
	public Cursor getAllEntry(){
		return db.query(DB_TABLE, new String[]{"_id", KEYNAME, KEYAGE}, null, null, null, null, null);
	}
	public Cursor getEntryAt(String name){
		
		String where = "name = ?";
		String []args = {name};
		return db.query(DB_TABLE, new String[]{"_id",KEYNAME,KEYAGE}, where , args, null, null, null);
	}
}
